import { getTTSTaskStatus, TTSTaskStatus, type TTSTaskInfo } from '@/api/ai/tts'

export interface PollingOptions {
  interval?: number;  // 轮询间隔，默认2000ms
  maxAttempts?: number;  // 最大轮询次数，默认300次（10分钟）
  onStatusChange?: (taskInfo: TTSTaskInfo) => void;  // 状态变化回调
  onError?: (error: Error) => void;  // 错误回调
}

export interface PollingResult {
  success: boolean;
  taskInfo?: TTSTaskInfo;
  error?: Error;
}

/**
 * TTS任务状态轮询器
 */
export class TTSTaskPolling {
  private taskId: number;
  private options: Required<PollingOptions>;
  private pollingTimer: number | null = null;
  private attempts = 0;
  private isPolling = false;

  constructor(taskId: number, options: PollingOptions = {}) {
    this.taskId = taskId;
    this.options = {
      interval: options.interval ?? 2000,
      maxAttempts: options.maxAttempts ?? 300,
      onStatusChange: options.onStatusChange ?? (() => {}),
      onError: options.onError ?? (() => {})
    };
  }

  /**
   * 开始轮询
   */
  async start(): Promise<PollingResult> {
    if (this.isPolling) {
      return { success: false, error: new Error('轮询已在进行中') };
    }

    this.isPolling = true;
    this.attempts = 0;

    return new Promise((resolve) => {
      const poll = async () => {
        try {
          this.attempts++;
          
          const response = await getTTSTaskStatus(this.taskId);
          
          if (!response.success) {
            throw new Error(response.message || '获取任务状态失败');
          }

          const taskInfo = response.data;
          
          // 通知状态变化
          this.options.onStatusChange(taskInfo);

          // 检查是否完成
          if (taskInfo.status === TTSTaskStatus.COMPLETED) {
            this.stop();
            resolve({ success: true, taskInfo });
            return;
          }

          // 检查是否失败
          if (taskInfo.status === TTSTaskStatus.FAILED) {
            this.stop();
            const error = new Error(taskInfo.errorMessage || '任务执行失败');
            resolve({ success: false, error, taskInfo });
            return;
          }

          // 检查是否超过最大尝试次数
          if (this.attempts >= this.options.maxAttempts) {
            this.stop();
            const error = new Error('任务轮询超时');
            resolve({ success: false, error, taskInfo });
            return;
          }

          // 继续轮询
          this.pollingTimer = window.setTimeout(poll, this.options.interval);
          
        } catch (error) {
          const err = error as Error;
          this.options.onError(err);
          
          // 如果是网络错误或临时错误，继续重试
          if (this.attempts < this.options.maxAttempts) {
            this.pollingTimer = window.setTimeout(poll, this.options.interval);
          } else {
            this.stop();
            resolve({ success: false, error: err });
          }
        }
      };

      // 开始第一次轮询
      poll();
    });
  }

  /**
   * 停止轮询
   */
  stop(): void {
    if (this.pollingTimer) {
      clearTimeout(this.pollingTimer);
      this.pollingTimer = null;
    }
    this.isPolling = false;
  }

  /**
   * 获取当前轮询状态
   */
  getStatus(): { isPolling: boolean; attempts: number } {
    return {
      isPolling: this.isPolling,
      attempts: this.attempts
    };
  }
}

/**
 * 便捷的轮询函数
 */
export const pollTTSTask = (taskId: number, options?: PollingOptions): TTSTaskPolling => {
  return new TTSTaskPolling(taskId, options);
};